package edu.tgc.service.system;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.abyss.common.annotation.Log;
import org.abyss.common.service.CommonCrudService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import edu.tgc.entity.system.SysPermission;
import edu.tgc.entity.system.SysRole;

@Log(value = "角色")
@Service
public class SysRoleService extends CommonCrudService<SysRole, UUID> {

    public Set<GrantedAuthority> getAuthorities(SysRole sysRole) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        if (!CollectionUtils.isEmpty(sysRole.getPermissions())) {
            for (SysPermission sysPermission : sysRole.getPermissions()) {
                if (sysPermission.getEnabled()) {
                    authorities.add(new SimpleGrantedAuthority(sysPermission.getCodePath()));
                }
            }
        }
        return authorities;
    }

    public void setPermissions(UUID id, Set<String> Ids) {
        SysRole entity = this.baseRepository.findOne(id);
        HashSet<SysPermission> entitys = new HashSet<>();
        if (Ids != null) {
            for (String entityId : Ids) {
                entitys.add(new SysPermission(UUID.fromString(entityId)));
            }
        }
        entity.setPermissions(entitys);
        this.baseRepository.saveAndFlush(entity);
    }

}
